<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\shouyin\model\Course as CourseModel;
use app\finance\model\Account as AccountModel;
use app\user\model\User as UserModel;
use app\system\model\systemUser as systemUserModel;
use app\shouyin\model\UserCard as UserCardModel;
use app\shouyin\model\UserBalanceLog as UserBalanceLogModel;
use app\product\model\Project as ProjectModel;
use app\product\model\Product as ProductModel;
use app\shouyin\model\UserCardLog as UserCardLogModel;
use app\shouyin\model\UserCardDetailLog as UserCardDetailLogModel;
use think\Db;
class Treatment extends Admin
{
    protected $hisiModel = 'UserCard';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize()
    {
        parent::initialize();
        $admin = systemUserModel::get(ADMIN_ID);

        $this->assign('admin_type',$admin['type']);

        // $this->assign('admin_type',$admin['type']);
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $where = [];

            $where['shop_id'] = session('shop_id');

            // 会员
            $users = UserModel::getSelect(UserModel::all());
            $this->assign('users', $users);
            $account_arr = AccountModel::where('status',1)->all();
            $account_arr[] = ['id' => -2, 'name' => "赠送"];
            $account_arr[] = ['id' => -5, 'name' => "会员卡赠送"];
            $accounts = AccountModel::getSelect($account_arr);

            $this->assign('accounts', $accounts);
            // 顾问
            $admins = systemUserModel::where($where)->all();
            $advisers = [];
            $technician = [];
            foreach ($admins as $key => $value) {
                if($value['type'] == '顾问'){
                    $advisers[] = $value;
                }else if($value['type'] == '美容师'){
                    $technician[] = $value;
                }
            }

            $this->assign('advisers', systemUserModel::getSelect($advisers));
            $this->assign('technicians', systemUserModel::where('type', 7)->where('shop_id',session('shop_id'))->field('id as value,nick as name')->all());
            $this->assign('courses', CourseModel::getSelect(CourseModel::where('status',1)->all()));

        }
    }
    public function add()
    {
        if ($this->request->isPost()) {

            $postData = $this->request->post();
            Db::startTrans();
            try {
                // echo 1;
                UserCardModel::create($postData);
                $meirongshi = Db::name('system_user')->where('id','in',$postData['technician_id'])->column('id,nick');
                $CourseModel = new CourseModel;
                $card = $CourseModel->get($postData['course_id']);
                $userModel = new UserModel;
                $userBalance = $userModel->getUserBalance($postData['user_id'],1);
                $userBalanceZeng = $userModel->getUserBalance($postData['user_id'],2);
                // halt($postData['account_id']);

               if($postData['account_id'] == 0){  // 余额支付
                    if($userBalance < $postData['price1']){
                        throw new \Exception("余额不足", 1);
                    }
                    if($postData['q1'] < $postData['price1']){
                        throw new \Exception("会员卡不支持定金付款方式", 1);
                    }
                    $log = [
                        'user_id' => $postData['user_id'],
                        'type' => 4,
                        'price' => $postData['price1'],
                        'sn' => $postData['sn'],
                        'is_give' => 1,
                    ];
                    $UserBalanceLogModel = new UserBalanceLogModel;
                    $UserBalanceLogModel->save($log);
                    $pay_type = '会员卡';
                }else if($postData['account_id'] == -5){  // 会员卡赠送余额
                    $pay_type = '会员卡赠送余额';
                    if($userBalanceZeng < $postData['price1']){
                        throw new \Exception("会员卡赠送余额不足", 1);
                    }
                    if($postData['q1'] < $postData['price1']){
                        throw new \Exception("赠送会员卡不支持定金付款方式", 1);
                    }
                    $log = [
                        'user_id' => $postData['user_id'],
                        'type' => 4,
                        'price' => $postData['price1'],
                        'sn' => $postData['sn'],
                        'is_give' => 2,
                    ];
                    $UserBalanceLogModel = new UserBalanceLogModel;
                    $UserBalanceLogModel->save($log);
                }else if( $postData['account_id'] == -2){  // 赠送

                    $pay_type = '赠送';

                }else{
                    $sys = [
                        'sn' => $postData['sn'],
                        'type' => 8,
                        'account_id' => $postData['account_id'],
                        'shop_id' => $postData['shop_id'],
                        // 'price' => $postData['price1'],   //  2020-09-02  尾款问题修改
                        'price' => $postData['q1'],
                        'createtime' => time(),
                        'updatetime' => time(),
                        'is_effective' => 1,
                        'user_id' => $postData['user_id'],
                        'cate' => 1,
                    ];
                    // echo 4;
                    Db::name('system_balance_log')->insert($sys);
                    $pay_type = '现金';
 
                }
                     // 绩效--------------------------------------------------
                    $jixiao = [];
                    $jixiao[] = [
                        'admin_id' => $postData['adviser_id'],
                        'user_id' => $postData['user_id'],
                        'project' => '疗程卡充值--'.$card['name'],
                        'num' => $postData['num'],
                        'price' => $postData['price1'],
                        'shougong' => 0,
                        'settlement' => $pay_type,
                        'shop_id' => $postData['shop_id'],
                        'admin_type' => '顾问',
                        'proportion' => 0,
                        'createtime' => date('Y-m-d H:i:s',time()),
                        'sn' => $postData['sn'],
                    ];
                    foreach ($meirongshi as $key => $value) {
                        $jixiao[] = [
                            'admin_id' => $key,
                            'user_id' => $postData['user_id'],
                            'project' => '疗程卡充值--'.$card['name'],
                            'num' => $postData['num'],
                            'price' => round(($postData['price1'] / count($meirongshi)),2),
                            'shougong' => 0,
                            'settlement' => $pay_type,
                            'shop_id' => $postData['shop_id'],
                            'admin_type' => '美容师',
                            'proportion' => 0,
                            'createtime' => date('Y-m-d H:i:s',time()),
                            'sn' => $postData['sn'],
                        ];
                    }
                    if(count($jixiao) > 0){
                        Db::name('achievements')->insertAll($jixiao);
                    }
                     // 绩效--------------------------------------------------
                     //
                if($card['type'] == 2){  // 疗程卡

                    $arr = json_decode($card['course_json']);
                    $log = [];
                    $detailLog = [];
                    foreach ($arr as $key => $value) {
                        for($i=1;$i <= round($value->num * $postData['num']);$i++){
                            $log[] = [
                                'user_id' => $postData['user_id'],
                                'pid' => $value->project,
                                'sn' => $postData['sn'],
                                'type' => 1,
                            ];
                        }
                        $start_num = UserCardLogModel::getUserCards($postData['user_id'], $value->project);
                        $price = ProjectModel::getProjectPrice($value->project);
                        $type = 1;
                        if ($postData['account_id'] == -2 || $postData['account_id'] == -5) {
                            $type = 4;
                        }
                        $detailLog[] = [
                            'userid'    => $postData['user_id'],
                            'course_id' => $postData['course_id'],
                            'cid'       => $value->project,
                            'price'     => $price * round($value->num * $postData['num']),
                            'start_num' => $start_num,
                            'use_num'   => round($value->num * $postData['num']),
                            'end_num'   => $start_num + round($value->num * $postData['num']),
                            'type'      => $type,
                            'createtime'=> time()
                        ];
                    }
                    UserCardDetailLogModel::insertAll($detailLog);

                    $UserCardLogModel = new UserCardLogModel;
                    $UserCardLogModel->saveAll($log);
                }else if($card['type'] == 3){   // 产品卡
                    $arr = json_decode($card['course_json']);
                    $log = [];
                    $detailLog = [];
                    foreach ($arr as $key => $value) {
                        for($i=1;$i <= round($value->num * $postData['num']);$i++){
                            $log[] = [
                                'user_id' => $postData['user_id'],
                                'pid' => $value->product,
                                'sn' => $postData['sn'],
                                'type' => 2,
                            ];

                        }
                        $start_num = UserCardLogModel::getUserCards($postData['user_id'], $value->product, 2);
                        $price = ProductModel::getProductPrice($value->product);
                        $detailLog[] = [
                            'userid'    => $postData['user_id'],
                            'course_id' => $postData['course_id'],
                            'cid'       => $value->product,
                            'price'     => $price * round($value->num * $postData['num']),
                            'start_num' => $start_num,
                            'use_num'   => round($value->num * $postData['num']),
                            'end_num'   => $start_num + round($value->num * $postData['num']),
                            'type'      => 1,
                            'cate'      => 2,
                            'createtime'=> time()
                        ];

                    }
                    UserCardDetailLogModel::insertAll($detailLog);
                    $UserCardLogModel = new UserCardLogModel;
                    $UserCardLogModel->saveAll($log);
                }else if($card['type'] == 1){ // 储值卡------留的接口，需要的时候再说

                }

                // echo 5;
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('保存成功', '');

        }

        $template = $this->request->param('template', 'form');

        return $this->fetch($template);
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $where['shop_id'] = session('shop_id');
            $data['data'] = UserCardModel::where($where)
                            ->field('*,user_id as user_id_text,shop_id as shop_id_text, finance_id as finance_id_text, adviser_id as adviser_id_text,technician_id as technician_text, cashier_id as cashier_id_text,account_id as account_id_text,course_id as course_id_text')
                            ->page($page)
                            ->limit($limit)
                            ->order('id desc')
                            ->select();
            $data['count'] = UserCardModel::where($where)->count('id');
            $data['code'] = 0;
            return json($data);
        }
        return $this->fetch();
    }


    public function edit()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();
        }

        $where = [];

        $db = Db::name('user_card');
        $pk = $db->getPk();
        $id = $this->request->param($pk);

        $where[]= [$pk, '=', $id];
        $where  = $this->getRightWhere($where);

        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                Db::name('user_card')->where($where)->update($postData);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('保存成功', '');
        }

        $formData = $db->where($where)->find();



        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        if(!is_empty($this->request->param('xx')) && $this->request->param('xx') == 2){
            // $card = $CourseModel->get($postData['course_id']);
            $formData['course_name'] = Db::name('course')->where('id',$formData['course_id'])->value('name');
            $formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');
            $formData['technician_name'] = implode(',', Db::name('system_user')->where('id','in',$formData['technician_id'])->column('nick'));
            $formData['adviser_name'] = Db::name('system_user')->where('id',$formData['adviser_id'])->value('nick');
            $formData['account_name'] = Db::name('account')->where('id',$formData['account_id'])->value('name');
            $this->view->engine->layout(false);
            // halt($formData);
            $this->assign('formData',$formData);
            return $this->fetch('dayin');
        }
        $formData['technician_id'] = Db::name('system_user')->where('id','in',$formData['technician_id'])->field('id as value, nick as name')->select();

        $this->assign('formData', $formData);

        $template = $this->request->param('template', 'form');

        return $this->fetch($template);
    }

    public function getAccountBalance()
    {
        $user_id = $this->request->param('user_id');
        $userModel = new UserModel;
        $balance = $userModel->getUserbalance($user_id,1);
        $balance2 = $userModel->getUserbalance($user_id,2);
        $data = [
            'balance' => $balance,
            'balance2' => $balance2,
        ];
        return json($data);
    }
    /**
     * 尾款 function
     *
     * @return void
     */
    public function wei()
    {
        $id = $this->request->param('id');
        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $info = UserCardModel::get($id);
            $where['sn'] = $info->sn;

            $data['data'] = Db::name('system_balance_log')
                            ->where($where)
                            ->page($page)
                            ->limit($limit)
                            ->order('id desc')
                            ->select();
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                $data['data'][$key]['account_id_text'] = Db::name('account')->where('id',$value['account_id'])->value('name');
            }
            $data['count'] = Db::name('system_balance_log')->where($where)->count('id');
            $data['code'] = 0;
            return json($data);
        }
        $this->assign('id',$id);
        return $this->fetch();
    }
    /**
     * 支付尾款 function
     *
     * @return void
     */
    public function addWei()
    {
        $id = $this->request->param('id');
        $formData = Db::name('user_card')->where('id',$id)->find();
        if($this->request->isPost()){
            $postData = $this->request->post();
            if($postData['q3'] <= 0){
                return $this->error('交款金额不能低于0元');
            }
            $editData = [
                'q1' => $formData['q1'] + $postData['q3'],
                'q2' => $formData['q2'] - $postData['q3'],
                'bak'=>  $formData['bak'].';'.$postData['bak']
            ];
            $sys = [
                'sn' => $postData['sn'],
                'type' => 8,
                'account_id' => $formData['account_id'],
                // 'price' => $postData['price1'],   //  2020-09-02  尾款问题修改
                'price' => $postData['q3'],
                'createtime' => time(),
                'updatetime' => time(),
                'is_effective' => 1,
                'user_id' => $formData['user_id'],
                'cate' => 1,
                'bak' => $postData['bak'],
                'shop_id' => $formData['shop_id'],
            ];
            Db::startTrans();
            try {
                Db::name('user_card')->where('id',$id)->update($editData);
                Db::name('system_balance_log')->insert($sys);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('保存成功', '');         
            
            // dump($editData);
            // halt($sys);
        }
        $formData['technician_id'] = Db::name('system_user')->where('id','in',$formData['technician_id'])->field('id as value, nick as name')->select();
        $this->assign('formData',$formData);
        return $this->fetch();
    }
}
